<?php
/** 
 * EGP Framework
 *
 * LICENSE
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 * @copyright  Copyright (c) 2008 (http://www.tblog.com.cn)
 * @license    http://www.gnu.org/licenses/gpl.html     GPL 3
 * @version    v1.0.0 Beta @ 2008-10-16
 */

!defined('EGP_LIB_DIR') && die('Access Deny!');

/**
 * 增强的 ini_set 扩展设置
 *
 * @package    classes
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 * @copyright  Copyright (c) 2008 (http://www.tblog.com.cn)
 * @license    http://www.gnu.org/licenses/gpl.html     GPL 3
 */
abstract class EGP_Ini
{

    /**
     * 增强的 ini_set 方法
     *
     * @param  string  $name
     * @param  mixed   $value
     * @return mixed
     */
    public static function set($name, $value)
    {
        $oldvar = ini_set($name, $value);
        if ($oldvar === false) {
            $obj = self::_referExt($name);
            $oldvar = $obj->_set($value);
        }
        return $oldvar;
    }

    /**
     * 增强的 ini_get 方法
     *
     * @param  string  $name
     * @return mixed
     */
    public static function get($name)
    {
        return self::_test($name) ? ini_get($name) : self::_referExt($name)->_get($name);
    }

    /**
     * 增强的 ini_restore 方法
     *
     * @param  string  $name
     */
    public static function restore($name)
    {
        self::_test($name) ? ini_restore($name) : self::_referExt($name)->_restore();
    }

    /**
     * 测试是否可通过 ini_set
     *
     * @param  string  $name
     * @return boolean
     */
    protected static function _test($name)
    {
        $oldvar = ini_get($name);
        $test = ini_set($name, 'test');
        $test !== false && ini_set($name, $oldvar) && $test = true;
        return $test;
    }

    /**
     * 加载 INI 扩展设置的实例
     *
     * @param  mixed  $name
     * @return EGP_Ini_Interface
     * @throws EGP_Exception
     */
    protected static function _referExt($name)
    {
        $classname = 'EGP_Ini_' . implode('', array_map('ucfirst', explode('_', $name)));
        if (EGP_Core::classExists($classname)) {
            $obj = new $classname();
            if ($obj instanceof EGP_Ini_Interface)
                return $obj;
        }
        throw new EGP_Exception("不支持的 INI 设置类型: '$name'");
    }

}